package vn.com.hung.notetaker.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import vn.com.hung.notetaker.config.Conf;

import com.google.common.io.Closeables;
import com.google.common.io.Files;

public class Tags {
    
    private static String tagFilePath;
    private static boolean autoSaveTrigged = false;
    private static List<String> tags = new ArrayList<String>();
    
    public static void loadTag(String filePath) {
        tagFilePath = filePath;
        if (! new File(tagFilePath).exists()) {
            return;
        }
        BufferedReader br = null; 
       try {
           br = Files.newReader(new File(filePath), Charset.forName("UTF-8"));
           String line;
           while ((line = br.readLine()) != null) {
               String[] tagStrs = line.split(",");
               tags.addAll(Arrays.asList(tagStrs));
           }
           Collections.sort(tags);
       } catch (IOException e) {
           DialogDisplayer.showDefaultErrorDialog("Cannot load tag file!");
       } finally {
           Closeables.closeQuietly(br);
       }
    }
    
    public static List<String> getTags() {
        return tags;
    }
    
    public static void saveTags() throws IOException {
        BufferedWriter bw = Files.newWriter(new File(tagFilePath), Charset.forName("UTF-8"));
        for (String tag : tags) {
            bw.write(tag + ",");
        }
    }
    
    public static void processTags(String csvTags) {
        if (csvTags == null || csvTags.length() < 2) {
            return;
        }
        String[] tags = csvTags.split(",");
        for (int i = 0; i < tags.length; i++) {
            insertTag(tags[i].trim());
        }
    }
    
    public static void printTags() {
        System.out.println("print tags ===============================");
        for (String tag : tags) {
            System.out.println(tag);
        }
        System.out.println("end tags =================================");
    }
    public static void insertTag(String tag) {
        tag = tag.toLowerCase();
        int n = Collections.binarySearch(tags,tag);
        if (n < 0) {
           tags.add(-n-1, tag);
        }
    }
    public static void save() {
        if (tagFilePath == null) {
           tagFilePath = Conf.getDBPath() + "/tags.txt";
         }
        if (tags.isEmpty()) { // tag list is empty
            return;
        }
        BufferedWriter writer = null;
        try {
            writer = Files.newWriter(new File(tagFilePath), 
                    Charset.forName("UTF-8"));
            StringBuilder builder = new StringBuilder();
            for (String tag: tags) {
                builder.append(tag + ",");
            }
           writer.write( builder.substring(0, builder.length() -1));
        } catch (IOException e) {
            DialogDisplayer.showDefaultErrorDialog("Cannot save tag file!");
        } finally {
          Closeables.closeQuietly(writer);  
        }
    }
    
    public static void trigAutoSave() {
        if (!autoSaveTrigged) {
            autoSaveTrigged = true;
            Timer timer = new Timer();
            SaveTask t = new Tags.SaveTask();
            System.gc();
            // 5 minutes each run;
            timer.schedule(t, 0, 300000);
            
        } else {
            return;
        }
    }
    public static class SaveTask extends TimerTask {
        int runCount;

        @Override
        public void run() {
            runCount++;
            System.out.println("Auto Saving Tags");
            Tags.save();
        }
        
    }
    
}
